import math
import time
import requests
from common.logs import logger


def https_logger():
    logger_name = 'https'
    return logger(name=logger_name,
                  log_name=logger_name + time.strftime("_%Y-%m-%d.log", time.localtime()))


# 连接超时时间（秒）
connect_timeout = 5
# 请求超时时间（秒）
request_timeout = 5
# 默认返回结果
result = {'code': 0, 'msg': '', 'data': ''}


def get(url, decode_type='utf-8', **kwargs):
    r"""get请求url地址

    :param url: url地址
    :param decode_type: 解码方式 utf-8,unicode,gbk
    :param kwargs: timeout=connect_timeout, headers=kwargs['headers'],decode_type=kwargs['utf-8']
    :type kwargs: timeout=int ,headers=dict
    :return:
    :rtype: dict
    """
    # 重定向allow_redirects=True
    try:
        response = requests.get(url, timeout=connect_timeout, headers=kwargs['headers'])
        # 微妙microseconds
        response_time = math.ceil(response.elapsed.microseconds / 1000)
        if response_time > request_timeout * 1000:
            log_message = "http.get请求获取response超时 - code:202 | url:%s | 请求获取时间:" % (url, response_time)
            https_logger().error(log_message)
            return {'code': 202, 'msg': 'http.get请求获取response超时', 'data': ''}

        if response.status_code == 200:
            if decode_type == "unicode":
                decode_type = "unicode_escape"
            return {'code': 200, 'msg': 'http.get请求成功', 'data': response.content.decode(decode_type)}
        else:
            log_message = "http.get请求错误 - code:203 | url:%s | exception:%s" % (url, response)
            https_logger().error(log_message)
            return {'code': 203, 'msg': 'http.get请求返回发生错误', 'data': ''}
    except Exception as e:
        log_message = "https.get方法错误 - code:201 | url:%s | exception:%s" % (url, e)
        https_logger().error(log_message)
        return {'code': 201, 'msg': 'https.get方法错误', 'data': e}


def post(url, data=None, json=None, decode_type='utf-8', **kwargs):
    r"""post请求url地址

    :param url: url地址
    :param data: 字典形式的参数{'key1':'value1','key2':'value2'} 二选一
    :param json: json格式 二选一
    :param decode_type: 解码方式 utf-8,unicode,gbk
    :param kwargs: timeout=connect_timeout, headers=kwargs['headers'],decode_type=kwargs['utf-8']
    :type kwargs: timeout=int ,headers=dict
    :return:
    :rtype: dict
    """
    # 重定向allow_redirects=True

    try:
        if json is None:
            response = requests.post(url, data=data, timeout=connect_timeout, headers=kwargs['headers'])
        else:
            response = requests.post(url, json=json, timeout=connect_timeout, headers=kwargs['headers'])

        # 微妙microseconds
        response_time = math.ceil(response.elapsed.microseconds / 1000)
        if response_time > request_timeout * 1000:
            log_message = "http.post请求获取response超时 - code:202 | url:%s | 请求获取时间:" % (url, response_time)
            https_logger().error(log_message)
            return {'code': 202, 'msg': 'http.post请求获取response超时', 'data': ''}

        if response.status_code == 200:
            if decode_type == "unicode":
                decode_type = "unicode_escape"
            return {'code': 200, 'msg': 'http.post请求成功', 'data': response.content.decode(decode_type)}
        else:
            log_message = "http.post请求错误 - code:203 | url:%s | exception:%s" % (url, response)
            https_logger().error(log_message)
            return {'code': 203, 'msg': 'http.post请求返回发生错误', 'data': ''}
    except Exception as e:
        log_message = "https.post方法错误 - code:201 | url:%s | exception:%s" % (url, e)
        https_logger().error(log_message)
        return {'code': 201, 'msg': 'https.post方法错误', 'data': e}
